<?php
// +----------------------------------------------------------------------
// | 在我们年轻的城市里，没有不可能的事！
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://utils All rights reserved.
// +----------------------------------------------------------------------
// | Author : Jansen <6206574@qq.com>
// +----------------------------------------------------------------------
/**
 * 有道翻译驱动
 * 支持传入的config参数如下：
 *   projectId：string，必填，项目ID，即appKey
 * @package jansen\utils\translate\drivers
 */
namespace jansen\utils\translate\drivers;
use jansen\utils\translate\exception\YoudaoTranslateException;
class Youdao implements TranslateInterface{
    /**
     * @var string 项目ID，可在 应用管理 查看
     */
    private $projectId;
    /**
     * @var string $secretKey 密钥
     */
    private $secretKey;
    /**
     * @var int $timestamp 当前 UNIX 时间戳，可记录发起 API 请求的时间。
     */
    private $timestamp;
    /**
     * @var int $random 随机数
     */
    private $random;
    /**
     * @var string $endpoint API接口调用完整域名
     */
    private $endpoint = 'https://openapi.youdao.com/api';
    public function __construct(array $config){
        key_exists('projectId', $config) && $this->setProjectId($config['projectId']);
        key_exists('secretKey', $config) && $this->setSecretKey($config['secretKey']);
        $this->setRandom();
        $this->setTimestamp();
    }
    /**
     * 生成随机数
     * @author:Jansen <6206574@qq.com>
     */
    public function setRandom(){
        $this->random = rand(1000, 9999);
    }
    /**
     * 设置项目ID
     * @param string $id
     * @return void
     * @author:Jansen <6206574@qq.com>
     */
    public function setProjectId(string $id){
        $this->projectId = $id;
    }
    /**
     * 设置SecretKey
     * @param string $secretKey
     * @return void
     * @author:Jansen <6206574@qq.com>
     */
    public function setSecretKey(string $secretKey){
        $this->secretKey = $secretKey;
    }
    /**
     * 设置时间戳
     * @return void
     * @author:Jansen <6206574@qq.com>
     */
    public function setTimestamp(){
        $this->timestamp = time();
    }
    /**
     * 文本翻译
     * @param string $content   待翻译文本
     * @param string $target    目标语言
     * @param string $source    源语言
     * @return string
     * @author:Jansen <6206574@qq.com>
     */
    public function text(string $content, string $target='en', string $source='auto'){
        $query['q']         = $content;
        $query['from']      = $source;
        $query['to']        = $target;
        $query['appKey']    = $this->projectId;
        $query['salt']      = $this->random;
        $query['sign']      = $this->authorization($content);
        $query['signType']  = 'v3';
        $query['curtime']   = $this->timestamp;
        $httpClient = new \GuzzleHttp\Client();
        $response = $httpClient->post($this->endpoint, [
            'connect_timeout'   => 5,
            'timeout'           => 5,
            'form_params'       => $query
        ]);
        $result = json_decode($response->getBody()->getContents(), true);
        if ($result['errorCode'] > 0){
            throw new YoudaoTranslateException('', $result['errorCode']);
        }
        return $result['translation'][0];
    }
    /**
     * 计算签名
     * @param string $content 待翻译文本
     * @return string
     * @author:Jansen <6206574@qq.com>
     */
    private function authorization(string $content){
        $length = mb_strlen($content, 'utf-8');
        $input = $length <= 20 ? $content : (mb_substr($content, 0, 10) . $length . mb_substr($content, -10));
        return hash('SHA256', $this->projectId.$input.$this->random.$this->timestamp.$this->secretKey);
    }
}